Imports ValidationFramework
Imports System.Web

Public Class PersonMapper
  ' Methods
  Public Sub Delete(ByVal person As Person)
    If Not person.IsValid Then
      Throw New ArgumentException("Person is not valid.  Delete is not allowed.", "person")
    End If
    GetPeople.Remove(person)
    TrySaveToSession()
  End Sub

  Public Function GetAllPeople() As IList(Of Person)
    Return New List(Of Person)(GetPeople)
  End Function

  Private Function GetDefaultPeople() As PersonCollection
    Dim person1 As New Person()
    person1.FirstName = "John"
    person1.Id = 0
    person1.LastName = "Smith"
    person1.Age = 31
    person1.EmailAddress = "John.Smith@b.com"
    person1.PhoneNumber = "02-1234-1234"
    person1.CardType = 0
    person1.CreditCardNumber = "1234567890123456"
    person1.OrderTotal = 21.99
    Dim person2 As New Person()
    person1.Id = 1
    person2.FirstName = "Jane"
    person2.LastName = "Doe"
    person2.Age = 56
    person2.EmailAddress = "Jane.Doe@b.com"
    person2.PhoneNumber = "05-4224-7337"
    person2.CardType = 2
    person2.CreditCardNumber = "123456789012345"
    person2.OrderTotal = 56.22
    Dim list As New PersonCollection
    list.Add(person1)
    list.Add(person2)
    Return list
  End Function

  Public Function GetItem(ByVal id As Integer) As Person
    Return GetPeople.Item(id)
  End Function

  Private Function GetPeople() As PersonCollection
    If (PersonMapper.people Is Nothing) Then
      Dim context As HttpContext = HttpContext.Current
      If (Not context Is Nothing) Then
        Dim sessionObject As Object = context.Session.Item("people")
        If (Not sessionObject Is Nothing) Then
          PersonMapper.people = DirectCast(sessionObject, PersonCollection)
        End If
      End If
    End If
    If (PersonMapper.people Is Nothing) Then
      PersonMapper.people = GetDefaultPeople
      TrySaveToSession()
    End If
    Return PersonMapper.people
  End Function

  Public Sub Save(ByVal person As Person)
    If Not person.IsValid Then
      Throw New ArgumentException("Person is not valid.  Save is not allowed.", "person")
    End If
    GetPeople.Add(person)
    TrySaveToSession()
  End Sub

  Public Sub SaveOrUpdate(ByVal person As Person)
    If Not person.IsValid Then
      Throw New ArgumentException("Person is not valid.  SaveOrUpdate is not allowed.", "person")
    End If
    Dim collection As PersonCollection = GetPeople
    If collection.Contains(person) Then
      collection.Remove(person)
    End If
    collection.Add(person)
    TrySaveToSession()
  End Sub

  Private Sub TrySaveToSession()
    Dim context As HttpContext = HttpContext.Current
    If (Not context Is Nothing) Then
      context.Session.Item("people") = PersonMapper.people
    End If
  End Sub


  ' Fields
  Private Shared people As PersonCollection
End Class
